﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Diagnostics;
using Infinite.SharePoint.Reminder.Console.ProfessionalServicesSite;
using Infinite.SHarePoint.StaffingServices2010;

namespace Infinite.SharePoint.Reminder.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * GetAboutToExpireConsultantContracts()
             * Set the result to List variable
             * Create a function to send email for the account manager 
             *      with consultant name and expiry details
             */
            Reminder r = new Reminder();
            r.GetAboutToExpireConsultantContracts();
            //DateTime ed = Convert.ToDateTime("6/12/2012");
            r.SendReminderEmails();

        }
    }
    /// <summary>
    /// This class stores the consultant relevant consultant data from Sharepoint
    /// for reminding account managers
    /// </summary>
    class ConsultantData
    {
        public string firstName;
        public string lastName;
        public DateTime? startDate;
        public DateTime? endDate;
        public string accountManager;
        public string accountManagerEmail;
    }
    /// <summary>
    /// This class implements all the releavant methods for reminder functionality
    /// </summary>
    class Reminder
    {

        List<ConsultantData> ReminderConsultantList = new List<ConsultantData>();

        /// <summary>
        /// Send reminder emails based on the expiry date
        /// </summary>
        internal void SendReminderEmails()
        {
            string copyTo = ConfigurationManager.AppSettings["HRManager"];
            string staffingHead = ConfigurationManager.AppSettings["StaffingHead"];
            string netAdmin = ConfigurationManager.AppSettings["netAdmin"];
            string sendTo = string.Empty;
            // Create the message
            if (ReminderConsultantList.Count > 0)
            {
                foreach (var con in ReminderConsultantList)
                {
                    MailMessage msg = new MailMessage();
                    msg.From = new MailAddress("wssadmin@infinite-usa.com", "Staffing SharepointSite");
                    sendTo = con.accountManagerEmail;
                    msg.To.Add(sendTo);
                    msg.CC.Add(copyTo);
                    msg.CC.Add(staffingHead);
                    msg.Bcc.Add(netAdmin);
                    msg.Bcc.Add("LSubramani@Infinite-usa.com");

                    TimeSpan diffInDates = Convert.ToDateTime(con.endDate) - DateTime.Now;
                    int diffDays = diffInDates.Days;
                    if (Convert.ToDateTime(con.endDate).Date == DateTime.Now.Date)
                    {
                        msg.Subject = con.firstName + " " + con.lastName + "'s contract expires Today";
                        msg.Body = String.Format("Dear Mr {0}\n\nYour Consultant {1}'s contract is expiring Today\n\nRegards,\n Staffing Service Site", con.accountManager, con.firstName + ", " + con.lastName);
                    }
                    else if (Convert.ToDateTime(con.endDate).Date < DateTime.Now.Date)
                    {
                        msg.Subject = String.Format("{0}'s contract expired {1} days ago", con.firstName + " " + con.lastName, -diffDays);
                        msg.Body = String.Format("Dear Mr {0}\n\n Your Consultant {1}'s contract expired on {2}\n\n Regards,\n Staffing Service Site", con.accountManager, con.firstName + ", " + con.lastName, con.endDate.ToString());                    
                    }
                    else
                    {
                        msg.Subject = String.Format("{0}'s contract expires in {1} days", con.firstName + " " + con.lastName, diffDays);
                        msg.Body = String.Format("Dear Mr {0}\n\n Your Consultant {1}'s contract is expiring on {2}\n\n Regards,\n Staffing Service Site", con.accountManager, con.firstName + ", " + con.lastName, con.endDate.ToString());
                    }
                    // Send the message
                    SmtpClient smtpC = new SmtpClient("mail.infinite-usa.com");
                    smtpC.UseDefaultCredentials = true;
                    smtpC.Send(msg);
                }
            }
        }

        /// <summary>
        /// Gets all the listdata who have expiry date associated to them
        /// </summary>
        internal void GetAboutToExpireConsultantContracts()
        {
            StaffingDataContext dc = new StaffingDataContext(new Uri("http://connect.infinite-usa.com/professionalservices/staffing/_vti_bin/ListData.svc"));

            dc.Credentials = System.Net.CredentialCache.DefaultCredentials;
            var credentials = new System.Net.NetworkCredential();
            credentials.UserName = ConfigurationManager.AppSettings["UserName"];
            credentials.Password = ConfigurationManager.AppSettings["Password"];
            credentials.Domain = "ics";
            dc.Credentials = credentials;
            try
            {
                var source = dc.Consultant;

                foreach (var dev in source)
                {
                    if ((dev.ProjectEndDate < DateTime.Now.AddDays(30)) && (dev.ProjectEndDate > DateTime.Now.AddDays(-30))) 
                    {
                        string amEmail = ConfigurationManager.AppSettings[dev.AccountManagerId.ToString()];
                        string amName = " ";
                        if (amEmail == string.Empty)
                            amEmail = "0";
                        else
                            amName = amEmail.Substring(1,amEmail.IndexOf('@')-1);
                        ReminderConsultantList.Add(new ConsultantData
                        {
                            firstName = dev.FirstName,
                            lastName = dev.LastName,
                            endDate = dev.ProjectEndDate,
                            startDate = dev.ProjectStartDate,
                            accountManagerEmail = amEmail,
                            accountManager = amName
                        });
                        //string devName = dev.FirstName + " " + dev.LastName + " " + dev.ProjectEndDate + " " + ConfigurationManager.AppSettings[id];

                        //Console.WriteLine(devName);
                    }

                }
            }
            catch(Exception ex)
            {
                if (!EventLog.SourceExists("SharePointReminder"))
                    EventLog.CreateEventSource("SharePointReminder", "Application");

                EventLog.WriteEntry("SharePointReminder", "Application");
                EventLog.WriteEntry("SharePointReminder", ex.Message + "/n" + ex.InnerException, EventLogEntryType.Warning, 234);

            }
            //Console.ReadKey();
            //throw new NotImplementedException();
        }

        //TODO: should get this to work
        //static string GetAccountManagerName(int id)
        //{
        //    //UserProfile.GetUserProfileByIndexResult AccMgrProfileInfo;// = new UserProfile.GetUserProfileByIndexResult();
        //    //UserProfile.UserProfileServiceSoapClient uPSC = new UserProfile.UserProfileServiceSoapClient();
        //    PropertyData[] upProperties;
        //    GetUserProfileByIndexResult upiResult;

        //    UserProfileService ups = new UserProfileService();

        //    ups.Credentials = System.Net.CredentialCache.DefaultCredentials;


        //    //UserProfile.UserProfileServiceSoapClient
        //    //uPSC.ClientCredentials = System.Net.CredentialCache.DefaultCredentials;
        //    upiResult = ups.GetUserProfileByIndex(id);
        //    upProperties = upiResult.UserProfile;

        //    string result = "";
        //    for (int i = 0; i < upProperties.Length; i++)
        //    {
        //        if (upProperties[i].Name.Contains("first"))
        //            result = result + " " + upProperties[i].Values;
        //        else if (upProperties[i].Name.Contains("last"))
        //            result = result + " " + upProperties[i].Values;
        //    }
        //    return result;
        //    //return gAccMgr;
        //}
    }
}
